// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.
package com.netease.yunxin.app.im.welcome

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import com.netease.nimlib.sdk.NIMClient
import com.netease.yunxin.app.im.main.MainActivity
import com.netease.yunxin.kit.alog.ALog
import com.netease.yunxin.kit.common.ui.activities.BaseActivity
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSession
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

/** Welcome Page is launch page  */
class WelcomeActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        handleSSLHandshake()
        if (TextUtils.isEmpty(NIMClient.getCurrentAccount())) {
            startActivity(Intent(this, LoginActivity::class.java))
            finish()
            ALog.i("[WelcomeActivity] go login")
        } else {
            ALog.i("[WelcomeActivity] go main")
            showMainActivityAndFinish()
        }
    }

    private fun showMainActivityAndFinish() {
        val intent = Intent()
        intent.setClass(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
        this.startActivity(intent)
        finish()
    }

    override fun onBackPressed() {
    }

    fun handleSSLHandshake() {
        try {
            var trustAllCerts: Array<TrustManager> =
                arrayOf<TrustManager>(object : X509TrustManager {
                    override fun checkClientTrusted(p0: Array<out X509Certificate>?, p1: String?) {

                    }

                    override fun checkServerTrusted(p0: Array<out X509Certificate>?, p1: String?) {

                    }

                    override fun getAcceptedIssuers(): Array<X509Certificate?> {
                        val arrayOfNulls = arrayOfNulls<X509Certificate?>(0)
                        return arrayOfNulls
                    }

                })

            val sc: SSLContext = SSLContext.getInstance("TLS")
            // trustAllCerts信任所有的证书
            sc.init(null, trustAllCerts, SecureRandom())
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())

            HttpsURLConnection.setDefaultHostnameVerifier(object : HostnameVerifier {
                override fun verify(p0: String?, p1: SSLSession?): Boolean {
                    return true
                }

            })

        } catch (e: Exception) {

        }
    }

}